package com.chengliang.wenda.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.Map;

/**
 * 解析工具类
 */
public class ParseUtil {

    /**
     * 网站地址
     */
    private static final String WWW_URL="https://www.wenjuan.com";
    /**
     * 登录地址
     */
    private static final String LOGIN_URL=WWW_URL+"/jslogin/";

    private static final String PROJECT_LIST_URL="https://www.wenjuan.com/edit/ajax/list/project_list/?p_type=0&page=1&time_order=1&time_period=all&t=1563206238233&search_txt=";

    /**
     * 网站cookie信息
     */
    private static  Map cookies;


    public static JSONObject login(String phone, String password) throws IOException {
        //请求登录页面获取cookie信息
        cookies = Jsoup.connect(WWW_URL)
                .execute().cookies();

        Connection connect = Jsoup.connect(LOGIN_URL);
        //设置访问登录页面获取的cookie信息
        connect.cookies(cookies);
        //登录信息
        connect.data("emailorusername",phone);
        connect.data("password",password);
        //请求登录返回JSON信息
        // 成功案例：{"nexturl":"/list/?login_create=1","sessionid":"agihA1LYbSIdBxcO5d2c98e1","error":0,"emailorusername":"13648044517","saveme":""}
        // 失败案例：{"nexturl":"/list/?login_create=1","err_msg":"账号或密码错误","emailorusername":"13111864119","saveme":""}
        return JSONObject.parseObject(connect.post().body().text());
    }

    public static JSONArray list(){
        try {
            JSONObject jsonObject = JSONObject.parseObject(Jsoup.connect(PROJECT_LIST_URL).cookies(cookies).get().body().text());
            return jsonObject.getJSONArray("project_list");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void projectDetail(){

    }


    public static void main(String[] args) {
        try {
            //String elf1106sj = test("13648044517", "ELF1106sj");
            //String elf1106sj=test("13111864119","123456");
            //System.out.println(elf1106sj);

            JSONObject jsonObject = login("13648044517", "ELF1106sj");
            System.out.println(jsonObject.get("error"));
            if(jsonObject.get("err_msg") != null) {
                System.out.println("登录失败");
                return;
            }
            list();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
